package com.example.cloudcustomer.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Project: spring-cloud
 * @Package: com.example.cloudcustomer.interceptor
 * @Author: 壹陸捌
 * @Time: 2025 - 08 - 05 09 : 30
 * @Description: Feign拦截器
 */
@Configuration
public class FeignInterceptor {

    private final LoadBalancerClient loadBalancerClient;

    public FeignInterceptor(LoadBalancerClient loadBalancerClient) {
        this.loadBalancerClient = loadBalancerClient;
    }

    @Bean
    public RequestInterceptor requestInterceptor() {
        return template -> {
            String serviceId = template.feignTarget().name();
            ServiceInstance instance = loadBalancerClient.choose(serviceId);
            if (instance != null) {
                StringBuilder sb = new StringBuilder();
                sb.append(instance.isSecure() ? "https://" : "http://")
                        .append(instance.getHost())
                        .append(":")
                        .append(instance.getPort())
                        .append(template.path());
                System.out.println("完整的请求路径URL: " + sb.toString());
            } else {
                System.out.println("No instance available for service: " + serviceId);
            }
        };
    }
}